package org.jsets.fastboot.persistent.interceptor;

import org.apache.ibatis.binding.MapperMethod.ParamMap;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Invocation;

/**
 * 
 * 拦截器工具
 * @author wangjie
 *
 */
public class InterceptorUtils {

	protected static final String INVOCATION_METHOD_PREPARE = "prepare";
	protected static final String INVOCATION_METHOD_UPDATE = "update";
	protected static final String INVOCATION_METHOD_QUERY = "query";
	protected static final String ENTITY_PARAMETER_NAME = "param1";
	protected static final String CURRENT_USER_NAME = "system";
	
	protected static boolean isInsertSqlCommand(MappedStatement ms) {
		return SqlCommandType.INSERT.equals(ms.getSqlCommandType());
	}

	protected static boolean isUpdateSqlCommand(MappedStatement ms) {
		return SqlCommandType.UPDATE.equals(ms.getSqlCommandType());
	}
	
	protected static boolean isSelectSqlCommand(MappedStatement ms) {
		return SqlCommandType.SELECT.equals(ms.getSqlCommandType());
	}

	protected static boolean isPrepareInvocation(Invocation invocation) {
		return INVOCATION_METHOD_PREPARE.equals(invocation.getMethod().getName());
	}
	
	protected static boolean isUpdataInvocation(Invocation invocation) {
		return INVOCATION_METHOD_UPDATE.equals(invocation.getMethod().getName());
	}
	
	protected static boolean isQueryInvocation(Invocation invocation) {
		return INVOCATION_METHOD_QUERY.equals(invocation.getMethod().getName());
	}
	
	@SuppressWarnings("rawtypes")
	protected static Object getEntity(Object object) {
		if(object instanceof ParamMap) {
			ParamMap paramMap = (ParamMap)object;
			if(paramMap.containsKey(InterceptorUtils.ENTITY_PARAMETER_NAME)) {
				return paramMap.get(InterceptorUtils.ENTITY_PARAMETER_NAME);
			}
		}
		return object;
	}
}
